package com.app.controller;

import cn.hutool.json.JSONUtil;
import com.app.common.Result;
import com.app.enums.StatusCodeEnum;
import com.app.mapper.InvationCodeMapper;
import com.app.model.AdminUserModel;
import com.app.model.InvitationCodeModel;
import com.app.service.AdminUserService;
import com.app.service.IPurchaseCouponsRecordService;
import com.app.service.PayService;
import com.app.service.UserService;
import com.app.utils.TokenUtils;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/pay")
@Slf4j
public class PayController {


    @Autowired
    private UserService userService;

    @Autowired
    private WxPayService wxService;

    @Autowired
    private IPurchaseCouponsRecordService purchaseCouponsRecordService;

    @Autowired
    private PayService payService;
    @Autowired
    private AdminUserService adminUserService;

    @Value("${wx.pay.mchId}")
    private String mchId;
    @Value("${wx.new.pay.mchId}")
    private String newMchId;

    /**
     * 解析订单通知结果
     *
     * @param xmlData xml数据
     * @return {@link String}
     * @throws WxPayException wx支付例外
     */
    @PostMapping("/notify/order")
    @Transactional
    public Object parseOrderNotifyResult(@RequestBody String xmlData) throws Exception {
        final WxPayOrderNotifyResult notifyResult = this.wxService.switchoverTo(mchId).parseOrderNotifyResult(xmlData);
        log.info("【异步通知】处理后的数据data={}", JSONUtil.toJsonStr(notifyResult));
        //支付成功后升级为会员
        userService.completeVip(notifyResult.getOutTradeNo());
        return WxPayNotifyResponse.success("成功");
    }



    /**
     * 解析订单通知结果
     *
     * @param xmlData xml数据
     * @return {@link String}
     * @throws WxPayException wx支付例外
     */
    @PostMapping("/notify/recharge")
    @Transactional
    public Object parseRechargeNotifyResult(@RequestBody String xmlData) throws Exception {
        final WxPayOrderNotifyResult notifyResult = this.wxService.switchoverTo(newMchId).parseOrderNotifyResult(xmlData);
        log.info("【异步通知】处理后的数据data={}", JSONUtil.toJsonStr(notifyResult));
        purchaseCouponsRecordService.rechargeCallback(notifyResult.getOutTradeNo());
        return WxPayNotifyResponse.success("成功");
    }



    @GetMapping("getVipList")
    public Result getVipList(Integer page, Integer limit, String keyword, String startTime, String endTime, String areaId, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String adminId = TokenUtils.verify(token);
        if (adminId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel adminUser = adminUserService.getById(Integer.parseInt(adminId));
        if (adminUser == null) {
            return Result.error(405, "用户不存在");
        }
        String cityId = "";
        if (adminUser.getRoleId() == 3) {
            cityId = adminUser.getAreaId().toString();
        }
        if (adminUser.getRoleId() == 4) {
            areaId = adminUser.getAreaId().toString();
        }
        return Result.success(payService.getVipList(page, limit, keyword, startTime, endTime, areaId,cityId));
    }
}
